/**
 * 搜索按钮点击事件
 *
 * */
function countAll() {
    searchParams(paramsObj);
    var hospital = $("#hospital").val();

    if(hospital == 0) {
        var code = 0;
        var level = 0;
        if($("#block").val() != null && $("#block").val() != "" && $("#block").val() != 0) {
            code = $("#block").val();
            level = 0;
            if($("#province").val() != null && $("#province").val() != "") {
                code = $("#province").val();
                level = 1;
                if($("#city").val() != 0) {
                    code = $("#city").val();
                    level = 2;
                    if($("#district").val() != 0) {
                        code = $("#district").val();
                        level = 3;
                    }
                }
            }
        }
        getInfoList(code, level, paramsObj.itemCode, paramsObj.year);
    }else {
        getHospitalList(hospital, paramsObj.itemCode, paramsObj.year);
    }
};


/**
 * 根据区域编码和层级查询
 *
 * */
function getInfoList(code,level,itemCode,data){
    $.ajax({
        //todo
        url: '/medical-cloud/regionalDisease/areacode',
        type: 'get',
        data: 'areaCode=' + code + "&level=" + level + '&testKindCode=' + itemCode + '&year=' + data,
        async: false, //默认为true 异步
        dataType: 'json',
        error: function (data) {
            alert('error');
        },
        success: function (data) {
            var slowDiseaseStatistics = data.slowDiseaseStatisticsVos;
            initLoding('testPercent', slowDiseaseStatistics);
        }
    })
}

/**
 * 根据医院Id查询，精准查询
 *
 * */
function getHospitalList(hospId,itemcode,date){
    $.ajax({
        //todo
        url:'/medical-cloud/regionalDisease/showList',
        type:'get',
        data:'hospId='+hospId+'&testKindCode='+itemcode+'&year='+date,
        async : false, //默认为true 异步
        dataType : 'json',
        error:function(data){
            alert('error');
        },
        success:function(data){
            console.log(data);
            var slowDiseaseStatistics = data.data.slowDiseaseStatisticsVos;
            console.log(slowDiseaseStatistics);
            initLoding('testPercent',slowDiseaseStatistics);
        }
    });
}


//获取查询参数
function searchParams(params) {

    if ($("#year").val() != null && $("#year").val() != "") {
        params["year"] = $("#year option:selected").text();
    }
    var itemCode = '';
    itemCode = $('.active').attr('class');
    itemCode = itemCode.replace(/active/g, "");
    if (itemCode != null || itemCode != ""){
        itemCode = itemCode.replace(/\s/g, ",");
        itemCode = itemCode.slice(0,itemCode.length-1);
        params["itemCode"] = itemCode;
    }else{
        itemCode = "";
    }
    return params;
}



$(function(){
    paramsObj = new Object();
    var areaCode = '0';
    var level = '';
    var date1=new Date;
    var year= date1.getFullYear();
    var objOption = $('#year option');
    for (var i = 0; i < objOption.length; i++) {
        if (objOption[i].text == year) {
            $('#year').val(objOption[i].value);
            break;
        }
    }
//----------------------------------------------------------------------------------------------//
    function initPie(id){
        var myChart = echarts.init(document.getElementById(id));
        //配置色
        var rich1 = {
            big: {
                color: "#1F4261",
                align: 'center',
                fontSize: 16,
                fontWeight:'bold',
            },
            small: {
                color: "#1F4261",
                fontSize: 12,
                align: 'center',
            }
        };

        //  颜色集合
        var colorList = [
            '#12C49F', '#EEB965', '#5aa9f0'
        ];

        // 总和
        var total = {
            value: '\n\n252',
            name: '总人数'
        }

        var originalData = [{
            value: 55,
            name: '偏高'
        }, {
            value: 70,
            name: '偏低'
        }, {
            value: 25,
            name: "正常"
        }];

        echarts.util.each(originalData, function(item, index) {
            item.itemStyle = {
                normal: {
                    color: colorList[index]
                }
            };
        });

        option = {
            tooltip: {
                trigger: 'item',
                formatter: '{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                x : '84',
                y : 'center',
                align:'left',
                itemGap:20,
                data:[
                    {
                        name: '偏低',
                        // 设置文本为红色
                        textStyle: {
                            padding:[25,0,0,0],
                            rich: rich1
                        }
                    },
                    {
                        name: '偏高',
                        // 设置文本为红色
                        textStyle: {
                            rich: rich1,
                            padding:[25,0,0,0]
                        }
                    }
                ],
                formatter: function (name) {

                    return '{small|' + name + '}\n\n{big|256(50%)}';

                }
            },
            backgroundColor:'#ffffff',
            title: [{
                text: total.name,
                left: '76%',
                top: '42%',
                textAlign: 'center',
                textBaseline: 'middle',
                textStyle: {
                    color: '#1F4261',
                    fontWeight: 'bold',
                    fontSize: 12
                }
            }, {
                text: total.value,
                left: '76%',
                top: '40%',
                textAlign: 'center',
                textBaseline: 'middle',
                textStyle: {
                    color: '#408EDC',
                    fontWeight: 'bold',
                    fontSize: 28
                }
            }],
            series: [{
                hoverAnimation: false, //设置饼图默认的展开样式
                radius: [50, 70],
                center: ['77%', '50%'],
                name: 'pie',
                type: 'pie',
                selectedMode: 'single',
                selectedOffset: 16, //选中是扇区偏移量
                clockwise: true,
                startAngle: 90,
                itemStyle: {
                    normal: {
                        borderWidth: 3,
                        borderColor: '#ffffff',
                    },
                    emphasis: {
                        borderWidth: 0,
                        shadowBlur: 5,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.2)'
                    }
                },
                data: originalData
            }]
        };
        myChart.setOption(option, true);

    }
    function initBar(id){
        var barChart = echarts.init(document.getElementById(id));
        var dataAxis = ['0-20', '20-30', '30-40', '40-50','50-60','60-70','70以上'];
        var data = [15, 12, 21, 40, 33, 34, 48];
        option = {
            title: {
                text: '单位:岁',
                right:'140',
                bottom:'18',
                textStyle: {
                    color: '#4F5F65',
                    fontSize:'14',
                    fontWeight:'normal'
                }
            },
            xAxis: {
                type:'category',
                data: dataAxis,
                axisLabel: {
                    textStyle: {
                        color: '#969A9F'
                    }
                },
                axisTick: {
                    show: false
                },
                axisLine: {
                    show: false
                },
                z: 10
            },
            yAxis: {
                min:0,
                max:100,
                splitNumber:4,
                interval:25,
                splitLine:{
                    lineStyle:{
                        color:'#C8D8FA',
                        width:'2'
                    }
                },
                axisLine: {
                    show: false
                },
                axisTick: {
                    show: false
                },
                axisLabel: {
                    textStyle: {
                        color: '#969A9F'
                    }
                }
            },
            series: [
                {
                    type: 'bar',
                    barWidth: '22',
                    itemStyle: {
                        normal: {
                            color: '#5aa9f0'
                        }
                    },
                    data: data
                }
            ]
        };

        barChart.setOption(option, true);
    }



    //------------------------------------模板----------------------------------------------//
    //模板字符串
    var str = $("#temp").html();

    console.log(str);
    //模板编译函数
    var compiled = _.template('<div class="list_one"><h3><%=title%></h3><div class="pie"><div class="peopleNum"><div class="title"><h5><%=person_title%>测试人数</h5><a href="#"></a><span><%=person_title%>测试次数</span><i>异常标准:偏高偏低次数超过50%</i></div><div id="<%=index_num%>" class="pieNum"></div></div><div class="genderRatio"><div class="title"><h5><%=percent_title%>测试人数</h5></div><div id="<%=index_ratio%>"  class="ratioPie"></div></div></div><div class="bar"><h5>异常年龄段分布</h5><div id="<%=ageBar%>" class="ageBar"></div></div>');
    //得到json
    $('.checkList ul li').click(function(){
        $(".statisticsDetail").html('');

        searchParams(paramsObj);
        $.ajax({
            //todo
            url:'/medical-cloud/regionalDisease/areacode',
            type:'get',
            data:'areaCode='+areaCode+"&level="+level+'&testKindCode='+paramsObj.itemCode+'&year='+paramsObj.year,
            async : false, //默认为true 异步
            dataType : 'json',
            error:function(data){
                alert('error');
            },
            success:function(data) {
                // console.log(data);
                if (data.slowDiseaseStatisticsMsgs == null || this.value == "") {
                    return;
                } else {
                    var dataMsg = data.slowDiseaseStatisticsMsgs;
                    _.each(dataMsg, function (dictionary,i) {
                        dictionary.person_title = "";
                        dictionary.percent_title = "";
                        dictionary.index_num = 'personDIV'+ i;
                        dictionary.index_ratio = 'genderDIV'+ i;
                        dictionary.ageBar = 'ageBar'+ i;
                        _.each(dictionary.resultMsg,function(item){
                            // console.log(item.genderDiv.percentTitle);
                            dictionary.person_title += item.personDiv.personTitle;
                            dictionary.percent_title += item.genderDiv.percentTitle;
                        });
                        var domstr = compiled(dictionary);
                        // 上树
                        $(domstr).appendTo(".statisticsDetail");
                        console.log('personDIV'+i);
                        // console.log('genderDIV'+i);
                        console.log('ageBar'+i);
                        initPie('personDIV'+i);
                        initPie('genderDIV'+i);
                        initBar('ageBar'+i);
                    });
                }
            }
        });
    });

    /**
     * 后台获取下级列表
     * */
    function getLowerAreaList(id,code,level,itemcode,date){
        $.ajax({
            //todo
            url:'/medical-cloud/regionalDisease/areacode',
            type:'get',
            data:'areaCode='+code+"&level="+level+'&testKindCode='+itemcode+'&year='+date,
            async : false, //默认为true 异步
            dataType : 'json',
            error:function(data){
                alert('error');
            },
            success:function(data){
                var objs = document.getElementById(id);
                objs.options.length = 1;
                var area = eval('('+ data.areaCode +')');
                var slowDiseaseStatistics = data.slowDiseaseStatisticsVos;
                if(id == 'hospital'){
                    $.ajax({
                        //todo
                        url:'/medical-cloud/regionalDisease/showHospital',
                        type:'get',
                        data:'areaCode='+code+"&level="+level+'&testKindCode='+itemcode+'&year='+date,
                        async : false, //默认为true 异步
                        dataType : 'json',
                        error:function(data){
                            alert('error');
                        },
                        success:function(data){
                            console.log(data);
                            var objs = document.getElementById(id);
                            objs.options.length = 1;
                            area = data.data;
                            for(var i=0;i<area.length;i++){
                                var childOption = document.createElement("option");
                                childOption.value = area[i].id;
                                childOption.innerHTML = area[i].hospName;
                                objs.appendChild(childOption);

                            }
                        }
                    });
                }else{
                    for(var i=0;i<area.length;i++){
                        var childOption = document.createElement("option");
                        childOption.value = area[i].code;
                        childOption.innerHTML = area[i].name;
                        objs.appendChild(childOption);
                        // console.log(area[i]);
                    }
                }
                // initLoding('testPercent',slowDiseaseStatistics);
            }
        });
    }
    /**
     * 重置下级菜单
     * */

    function resetArea(level){
        if(level<1){
            var provinceArea = document.getElementById("province");
            provinceArea.options.length = 1;
        }
        if(level<2){
            var cityArea = document.getElementById("city");
            cityArea.options.length = 1;
        }
        if(level<3){
            var districtArea = document.getElementById("district");
            districtArea.options.length = 1;
        }
        if(level<4){
            var hospitalArea = document.getElementById("hospital");
            hospitalArea.options.length = 1;
        }
    }


    $(function () {
        $("#block").change(function () {
            searchParams(paramsObj);
            var hospitalId = $('');

            if (this.value == null || this.value == "") {
                resetArea(0);
            }else if(this.value == '0'){
                areaCode = this.value;
                level = '';
                getLowerAreaList("province", this.value, '',paramsObj.itemCode,paramsObj.year);
            } else {
                areaCode = this.value;
                level = 0;
                getLowerAreaList("province", this.value, 0,paramsObj.itemCode,paramsObj.year);
                resetArea(1);
            }
        });


        $("#province").change(function () {
            searchParams(paramsObj);

            if (this.value == null || this.value == "") {
                resetArea(1);
            } else {
                areaCode = this.value;
                level = 1;
                getLowerAreaList("city", this.value, 1,paramsObj.itemCode,paramsObj.year);
                resetArea(2);
            }
        });
        $("#city").change(function () {
            searchParams(paramsObj);
            if (this.value == null || this.value == "") {
                resetArea(2);
            } else {
                areaCode = this.value;
                level = 2;
                getLowerAreaList("district", this.value, 2,paramsObj.itemCode,paramsObj.year);
                resetArea(3);
            }
        });

        $("#district").change(function () {
            searchParams(paramsObj);
            if (this.value == null || this.value == "") {
                resetArea(3);
            } else {
                areaCode = this.value;
                level = 3;
                getLowerAreaList("hospital", this.value, 3,paramsObj.itemCode,paramsObj.year);
                resetArea(4);
            }
        });
        $("#hospital").change(function () {
            searchParams(paramsObj);
            var hospitalId = $(this).find("option:selected").val();

            if (this.value == null || this.value == "") {
                resetArea(3);
            } else {
                areaCode = this.value;
                level = 4;
                //getHospitalList(hospitalId,paramsObj.itemCode,paramsObj.year);
                resetArea(4);
            }
        });

        $("#year").change(function () {

            searchParams(paramsObj);
            // getLowerAreaList("hospital", areaCode, level,paramsObj.itemCode,paramsObj.year);
        });
    });



//-------------------------切换tab标签------------------------------------------------------//
    searchParams(paramsObj);
    areaDefault = $("#block option:selected").val();

    getLowerAreaList("province",areaDefault, 0,paramsObj.itemCode,paramsObj.year);

});

function initLoding(id,data){

    // console.log(data);
    var myChart = echarts.init(document.getElementById(id));
    // 设置配置色
    var rich = {
        blue: {
            color: "#408EDC",
            align: 'bottom',
            fontSize: 24,
            fontWeight:'bolder'
        },
        gray: {
            color: '#4F5F65',
            fontSize: 12,
            align: 'bottom'
        },
        dark:{
            color: '#4F5F65',
            fontSize: 12,
            align: 'bottom',
            padding: [0,5]
        }
    }
    //设置label样式
    var labelFromatter = {
        normal : {
            color:"#8377D1",
            label : {
                color:"#1F4261",
                textStyle:{
                    fontSize:14,
                    fontWeight: 'bold'
                }
            }
        }
    }
    var labelTop = {
        normal : {
            label : {
                show : true,
                position : 'center',
                formatter : function (params){
                    percent = params.percent.toFixed(0);
                    return '{blue|\n'+ params.value +'}{dark|/}{gray|'+ percent +'%}'
                },
                rich:rich
            },
            labelLine : {
                show : false
            }
        }
    };
    var labelBottom = {
        normal : {
            color: '#ecf2f8',
            label : {
                show : true,
                position : 'center',
                formatter : function (params){
                    return '区域测试总人数'
                },
                textStyle: {
                    baseline : 'center',
                    color:"#1F4261",
                    fontSize:'15',
                    fontWeight: 'bold',
                    fontFamily:'MicrosoftYaHei'
                }
            },
            labelLine : {
                show : false
            }
        },
        emphasis: {
            color: 'rgba(0,0,0,0)'
        }
    };
    var radius = [75, 69];
    // 设置配置项option
    option = {
        title : {
            text: ''
        },
        series : [
            {
                type : 'pie',
                center : ['15%', '40%'],
                radius : radius,
                x: '0%', // for funnel
                itemStyle : labelFromatter,
                data : [
                    {
                        name:90,
                        value:(data[0].totalCount - data[0].testCount),
                        itemStyle : {
                            normal : {
                                color: '#ecf2f8',
                                label : {
                                    show : true,
                                    position : 'center',
                                    formatter : function (params){
                                        return '区域测试总人数'
                                    },
                                    textStyle: {
                                        baseline : 'center',
                                        color:"#1F4261",
                                        fontSize:'15',
                                        fontWeight: 'bold',
                                        fontFamily:'MicrosoftYaHei'
                                    }
                                },
                                labelLine : {
                                    show : false
                                }
                            }
                        }
                    },
                    {
                        name:data[0].percent,
                        value:data[0].testCount,
                        itemStyle : labelTop
                    }
                ]
            },
            {
                type : 'pie',
                center : ['35%', '40%'],
                radius : radius,
                x:'20%', // for funnel
                itemStyle : labelFromatter,
                data : [
                    {
                        name:'',
                        value:(data[1].totalCount - data[1].testCount),
                        itemStyle : {
                            normal : {
                                color: '#ecf2f8',
                                label : {
                                    show : true,
                                    position : 'center',
                                    formatter : function (params){
                                        return '血压测试数'
                                    },
                                    textStyle: {
                                        baseline : 'center',
                                        color:"#1F4261",
                                        fontSize:'15',
                                        fontWeight: 'bold',
                                        fontFamily:'MicrosoftYaHei'

                                    }
                                },
                                labelLine : {
                                    show : false
                                }
                            },
                        }
                    },
                    {
                        name:data[1].percent,
                        value:data[1].testCount,
                        itemStyle : labelTop
                    }
                ]
            },
            {
                type : 'pie',
                center : ['55%', '40%'],
                radius : radius,
                x:'40%', // for funnel
                itemStyle : labelFromatter,
                data : [
                    {
                        name:'',
                        value:(data[2].totalCount - data[2].testCount),
                        itemStyle : {
                            normal : {
                                color: '#ecf2f8',
                                label : {
                                    show : true,
                                    position : 'center',
                                    formatter : function (params){
                                        return '血糖测试数'
                                    },
                                    textStyle: {
                                        baseline : 'center',
                                        color:"#1F4261",
                                        fontSize:'15',
                                        fontWeight: 'bold',
                                        fontFamily:'MicrosoftYaHei'

                                    }
                                },
                                labelLine : {
                                    show : false
                                }
                            },
                        }
                    },
                    {
                        name:data[2].percent,
                        value:data[2].testCount,
                        itemStyle : labelTop
                    }
                ]
            },
            {
                type : 'pie',
                center : ['75%', '40%'],
                radius : radius,
                x:'60%', // for funnel
                itemStyle : labelFromatter,
                data : [
                    {
                        name:'',
                        value:(data[3].totalCount - data[3].testCount),
                        itemStyle : {
                            normal : {
                                color: '#ecf2f8',
                                label : {
                                    show : true,
                                    position : 'center',
                                    formatter : function (params){
                                        return 'POCT测试数'
                                    },
                                    textStyle: {
                                        baseline : 'center',
                                        color:"#1F4261",
                                        fontSize:'15',
                                        fontWeight: 'bold',
                                        fontFamily:'MicrosoftYaHei'

                                    }
                                },
                                labelLine : {
                                    show : false
                                }
                            },
                        }
                    },
                    {
                        name:data[3].percent,
                        value:data[3].testCount,
                        itemStyle : labelTop
                    }
                ]
            }
        ]
    };

    // 设置加载等待隐藏
    // myChart.hideLoading();

    myChart.setOption(option);


}